<template>
  <div class="asset-detail-container">
    <n-card class="detail-card">
      <template #header>
        <div class="card-header">
          <h1>素材详情</h1>
          <div class="header-actions">
            <n-button @click="goBack">
              <template #icon><n-icon><ArrowBackOutline /></n-icon></template>
              返回
            </n-button>
          </div>
        </div>
      </template>
      
      <div v-if="loading" class="loading-container">
        <n-spin size="large" />
        <p>正在加载素材信息...</p>
      </div>
      
      <div v-else-if="!asset" class="error-container">
        <n-result status="404" title="素材不存在" description="找不到该素材或已被删除">
          <template #footer>
            <n-button @click="goBack">返回素材市场</n-button>
          </template>
        </n-result>
      </div>
      
      <div v-else class="asset-content">
        <div class="asset-main">
          <div class="asset-preview">
            <div class="preview-container">
              <img :src="asset.thumbnail" :alt="asset.name" />
              
              <div class="preview-controls" v-if="asset.previewImages && asset.previewImages.length > 0">
                <div class="preview-thumbnails">
                  <div 
                    v-for="(img, index) in asset.previewImages" 
                    :key="index"
                    class="preview-thumbnail"
                    :class="{ active: currentPreviewIndex === index }"
                    @click="currentPreviewIndex = index"
                  >
                    <img :src="img" :alt="`预览 ${index + 1}`" />
                  </div>
                </div>
              </div>
            </div>
            
            <div class="asset-actions">
              <n-button-group>
                <n-button type="primary" @click="downloadAsset" :loading="downloading" :disabled="!canDownload">
                  <template #icon><n-icon><DownloadOutline /></n-icon></template>
                  {{ asset.price > 0 ? `购买 (${asset.price} 积分)` : '免费下载' }}
                </n-button>
                <n-button @click="previewAsset" :disabled="!canPreview">
                  <template #icon><n-icon><EyeOutline /></n-icon></template>
                  预览效果
                </n-button>
              </n-button-group>
              
              <n-space>
                <n-button text @click="toggleFavorite">
                  <template #icon>
                    <n-icon :color="isFavorite ? '#ff4d4f' : ''">
                      <component :is="isFavorite ? HeartFilled : HeartOutline" />
                    </n-icon>
                  </template>
                  {{ isFavorite ? '已收藏' : '收藏' }}
                </n-button>
                <n-button text @click="shareAsset">
                  <template #icon><n-icon><ShareSocialOutline /></n-icon></template>
                  分享
                </n-button>
                <n-button text @click="reportAsset">
                  <template #icon><n-icon><FlagOutline /></n-icon></template>
                  举报
                </n-button>
              </n-space>
            </div>
          </div>
          
          <div class="asset-info">
            <div class="asset-header">
              <h2>{{ asset.name }}</h2>
              <div class="asset-badges">
                <n-tag v-if="asset.price === 0" type="success">免费</n-tag>
                <n-tag v-else type="warning">{{ asset.price }} 积分</n-tag>
                <n-tag v-if="asset.isNew" type="info">新品</n-tag>
                <n-tag :type="getLicenseTagType(asset.license)">{{ getLicenseLabel(asset.license) }}</n-tag>
                <n-tag v-if="asset.isFeatured" type="primary" size="small">精选</n-tag>
              </div>
            </div>
            
            <div class="asset-meta">
              <div class="meta-item">
                <n-icon><PersonOutline /></n-icon>
                <span>创作者:</span>
                <n-button text @click="viewCreator">{{ asset.creator }}</n-button>
              </div>
              <div class="meta-item">
                <n-icon><CalendarOutline /></n-icon>
                <span>发布时间:</span>
                <span>{{ formatDate(asset.createdAt) }}</span>
              </div>
              <div class="meta-item">
                <n-icon><DownloadOutline /></n-icon>
                <span>下载次数:</span>
                <span>{{ asset.downloadCount }}</span>
              </div>
              <div class="meta-item">
                <n-icon><EyeOutline /></n-icon>
                <span>查看次数:</span>
                <span>{{ asset.viewCount }}</span>
              </div>
            </div>
            
            <div class="asset-rating">
              <div class="rating-header">
                <h3>评分</h3>
                <span>{{ asset.rating.toFixed(1) }}</span>
              </div>
              <div class="rating-stars">
                <n-rate :value="asset.rating" readonly allow-half />
                <span>({{ asset.ratingCount }}人评分)</span>
              </div>
              <div class="rating-distribution">
                <div v-for="i in 5" :key="i" class="rating-bar">
                  <span>{{ 6 - i }}星</span>
                  <div class="bar-container">
                    <div 
                      class="bar-fill" 
                      :style="{ width: `${getDistributionPercentage(6 - i)}%` }"
                    ></div>
                  </div>
                  <span>{{ asset.ratingDistribution[6 - i] || 0 }}</span>
                </div>
              </div>
            </div>
            
            <div class="asset-tags">
              <h3>标签</h3>
              <div class="tags-list">
                <n-tag 
                  v-for="tag in asset.tags" 
                  :key="tag" 
                  :bordered="false"
                  @click="searchByTag(tag)"
                >
                  {{ tag }}
                </n-tag>
              </div>
            </div>
          </div>
        </div>
        
        <n-divider />
        
        <div class="asset-details">
          <n-tabs type="line" animated>
            <n-tab-pane name="description" tab="素材描述">
              <div class="description-content">
                <div v-html="formattedDescription"></div>
              </div>
            </n-tab-pane>
            
            <n-tab-pane name="specifications" tab="规格参数">
              <div class="specifications-content">
                <div class="spec-group">
                  <h3>基本信息</h3>
                  <div class="spec-table">
                    <div class="spec-row">
                      <div class="spec-label">素材类型</div>
                      <div class="spec-value">{{ getAssetTypeLabel(asset.type) }}</div>
                    </div>
                    <div class="spec-row">
                      <div class="spec-label">文件格式</div>
                      <div class="spec-value">{{ asset.fileFormat }}</div>
                    </div>
                    <div class="spec-row">
                      <div class="spec-label">文件大小</div>
                      <div class="spec-value">{{ formatFileSize(asset.fileSize) }}</div>
                    </div>
                    <div class="spec-row" v-if="asset.dimensions">
                      <div class="spec-label">尺寸</div>
                      <div class="spec-value">{{ asset.dimensions.width }} × {{ asset.dimensions.height }} px</div>
                    </div>
                    <div class="spec-row" v-if="asset.duration">
                      <div class="spec-label">时长</div>
                      <div class="spec-value">{{ formatDuration(asset.duration) }}</div>
                    </div>
                  </div>
                </div>
                
                <div class="spec-group" v-if="asset.requirements">
                  <h3>使用要求</h3>
                  <div class="spec-table">
                    <div class="spec-row">
                      <div class="spec-label">软件版本</div>
                      <div class="spec-value">{{ asset.requirements.softwareVersion || '无特殊要求' }}</div>
                    </div>
                    <div class="spec-row">
                      <div class="spec-label">插件依赖</div>
                      <div class="spec-value">{{ asset.requirements.plugins || '无' }}</div>
                    </div>
                  </div>
                </div>
                
                <div class="spec-group">
                  <h3>许可信息</h3>
                  <div class="license-info">
                    <p>{{ getLicenseDescription(asset.license) }}</p>
                  </div>
                </div>
              </div>
            </n-tab-pane>
            
            <n-tab-pane name="comments" tab="用户评价">
              <div class="comments-content">
                <div class="comment-form" v-if="isLoggedIn">
                  <h3>发表评价</h3>
                  <div class="rating-input">
                    <span>评分:</span>
                    <n-rate v-model:value="userRating" />
                  </div>
                  <n-input 
                    v-model:value="commentContent" 
                    type="textarea" 
                    placeholder="分享你对这个素材的看法..." 
                    :autosize="{ minRows: 3, maxRows: 6 }"
                  />
                  <div class="form-actions">
                    <n-button type="primary" @click="submitComment" :disabled="!canSubmitComment">
                      发表评价
                    </n-button>
                  </div>
                </div>
                <div class="login-prompt" v-else>
                  <p>请<n-button text @click="goToLogin">登录</n-button>后发表评价</p>
                </div>
                
                <n-divider />
                
                <div class="comments-list">
                  <h3>用户评价 ({{ asset.comments.length }})</h3>
                  
                  <div v-if="asset.comments.length === 0" class="empty-comments">
                    <n-empty description="暂无评价">
                      <template #extra>
                        <p>成为第一个评价这个素材的用户吧！</p>
                      </template>
                    </n-empty>
                  </div>
                  
                  <div v-else class="comment-items">
                    <div v-for="comment in asset.comments" :key="comment.id" class="comment-item">
                      <div class="comment-header">
                        <div class="comment-user">
                          <n-avatar :src="comment.userAvatar" round />
                          <span class="username">{{ comment.username }}</span>
                        </div>
                        <div class="comment-rating">
                          <n-rate :value="comment.rating" readonly size="small" />
                        </div>
                      </div>
                      <div class="comment-content">{{ comment.content }}</div>
                      <div class="comment-footer">
                        <span class="comment-time">{{ formatDate(comment.createdAt) }}</span>
                        <div class="comment-actions">
                          <n-button text size="small" @click="likeComment(comment)">
                            <template #icon>
                              <n-icon :color="comment.isLiked ? '#18a058' : ''">
                                <ThumbsUpOutline />
                              </n-icon>
                            </template>
                            {{ comment.likes }}
                          </n-button>
                          <n-button text size="small" @click="replyComment(comment)">
                            <template #icon><n-icon><ChatbubbleOutline /></n-icon></template>
                            回复
                          </n-button>
                        </div>
                      </div>
                      
                      <div v-if="comment.replies && comment.replies.length > 0" class="comment-replies">
                        <div v-for="reply in comment.replies" :key="reply.id" class="reply-item">
                          <div class="reply-header">
                            <div class="reply-user">
                              <n-avatar :src="reply.userAvatar" round size="small" />
                              <span class="username">{{ reply.username }}</span>
                            </div>
                          </div>
                          <div class="reply-content">{{ reply.content }}</div>
                          <div class="reply-footer">
                            <span class="reply-time">{{ formatDate(reply.createdAt) }}</span>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                  
                  <div v-if="asset.comments.length > 5" class="comments-pagination">
                    <n-pagination 
                      v-model:page="commentPage" 
                      :page-count="commentTotalPages" 
                      :page-slot="5"
                    />
                  </div>
                </div>
              </div>
            </n-tab-pane>
          </n-tabs>
        </div>
        
        <div class="related-assets">
          <div class="section-header">
            <h2>相关素材</h2>
            <n-button text @click="viewMoreRelated">查看更多</n-button>
          </div>
          
          <div class="related-grid">
            <n-card
              v-for="relatedAsset in relatedAssets"
              :key="relatedAsset.id"
              class="asset-card"
              hoverable
              @click="viewAsset(relatedAsset.id)"
            >
              <div class="asset-thumbnail">
                <img :src="relatedAsset.thumbnail" :alt="relatedAsset.name" />
                <div class="asset-badges">
                  <n-tag v-if="relatedAsset.price === 0" type="success" size="small">免费</n-tag>
                  <n-tag v-else type="warning" size="small">{{ relatedAsset.price }} 积分</n-tag>
                </div>
              </div>
              <div class="asset-info">
                <h3>{{ relatedAsset.name }}</h3>
                <div class="asset-meta">
                  <div class="asset-creator">
                    <span>{{ relatedAsset.creator }}</span>
                  </div>
                  <div class="asset-rating">
                    <n-rate :value="relatedAsset.rating" readonly size="small" />
                  </div>
                </div>
              </div>
            </n-card>
          </div>
        </div>
      </div>
    </n-card>
    
    <!-- 预览模态框 -->
    <n-modal v-model:show="showPreview" preset="card" style="width: 80%; max-width: 1200px;" title="素材预览">
      <div class="preview-modal-content">
        <img v-if="asset && asset.previewImages && asset.previewImages.length > 0" 
             :src="asset.previewImages[currentPreviewIndex]" 
             :alt="asset.name" 
             style="max-width: 100%; max-height: 70vh; object-fit: contain;" />
        <div class="preview-description">
          <h3>{{ asset ? asset.name : '' }}</h3>
          <p>{{ asset ? asset.shortDescription : '' }}</p>
        </div>
      </div>
    </n-modal>
    
    <!-- 分享模态框 -->
    <n-modal v-model:show="showShare" preset="card" style="width: 400px;" title="分享素材">
      <div class="share-modal-content">
        <p>分享这个素材到：</p>
        <div class="share-buttons">
          <n-button @click="shareToSocial('weixin')">
            <template #icon><n-icon><LogoWechat /></n-icon></template>
            微信
          </n-button>
          <n-button @click="shareToSocial('weibo')">
            <template #icon><n-icon><LogoWeibo /></n-icon></template>
            微博
          </n-button>
          <n-button @click="shareToSocial('qq')">
            <template #icon><n-icon><LogoTencent /></n-icon></template>
            QQ
          </n-button>
        </div>
        <n-divider />
        <div class="share-link">
          <p>或复制链接：</p>
          <n-input-group>
            <n-input :value="shareLink" readonly />
            <n-button type="primary" @click="copyShareLink">复制</n-button>
          </n-input-group>
        </div>
      </div>
    </n-modal>
    
    <!-- 举报模态框 -->
    <n-modal v-model:show="showReport" preset="card" style="width: 500px;" title="举报素材">
      <div class="report-modal-content">
        <p>请选择举报原因：</p>
        <n-radio-group v-model:value="reportReason">
          <n-space vertical>
            <n-radio v-for="reason in reportReasons" :key="reason.value" :value="reason.value">
              {{ reason.label }}
            </n-radio>
          </n-space>
        </n-radio-group>
        <n-input 
          v-if="reportReason === 'other'" 
          v-model:value="reportDetail" 
          type="textarea" 
          placeholder="请详细描述举报原因..." 
          :autosize="{ minRows: 3, maxRows: 6 }"
          style="margin-top: 16px;"
        />
        <div class="modal-actions">
          <n-button @click="cancelReport">取消</n-button>
          <n-button type="primary" @click="handleReportSubmit" :disabled="!canSubmitReport">
            提交举报
          </n-button>
        </div>
      </div>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useMessage } from 'naive-ui'
import {
  NCard,
  NButton,
  NButtonGroup,
  NIcon,
  NDivider,
  NSpace,
  NTabs,
  NTabPane,
  NTag,
  NEmpty,
  NSpin,
  NResult,
  NRate,
  NAvatar,
  NInput,
  NInputGroup,
  NModal,
  NRadio,
  NRadioGroup,
  NPagination
} from 'naive-ui'
import {
  ArrowBackOutline,
  DownloadOutline,
  EyeOutline,
  HeartOutline,
  ShareSocialOutline,
  FlagOutline,
  PersonOutline,
  CalendarOutline,
  ThumbsUpOutline,
  ChatbubbleOutline,
  LogoWechat,
  Heart as HeartFilled
} from '@vicons/ionicons5'
import { h } from 'vue'

// 自定义图标组件
const LogoTencent = () => {
  return h('svg', {
    xmlns: 'http://www.w3.org/2000/svg',
    viewBox: '0 0 24 24',
    width: '1em',
    height: '1em'
  }, [
    h('path', {
      fill: 'currentColor',
      d: 'M11.987 1.576c-5.761 0-10.427 4.194-10.427 9.373 0 3.262 1.636 6.111 4.66 7.916v2.522c0 .043.004.087.013.129a.457.457 0 0 0 .463.407.456.456 0 0 0 .272-.089l2.599-1.947h2.421c5.76 0 10.426-4.194 10.426-9.373s-4.667-9.373-10.427-9.373zm-1.894 9.348l-.393 2.095a.175.175 0 0 1-.339.001l-.392-2.095a1.635 1.635 0 0 0-1.634-1.348h-.068a.175.175 0 0 0-.173.21l.957 4.299a1.986 1.986 0 0 0 1.944 1.562h.232a1.986 1.986 0 0 0 1.944-1.562l.957-4.299a.175.175 0 0 0-.173-.21h-.068a1.635 1.635 0 0 0-1.634 1.348zm7.302-1.348h-.068a1.635 1.635 0 0 0-1.634 1.348l-.393 2.095a.175.175 0 0 1-.339.001l-.392-2.095a1.635 1.635 0 0 0-1.634-1.348h-.068a.175.175 0 0 0-.173.21l.957 4.299a1.986 1.986 0 0 0 1.944 1.562h.232a1.986 1.986 0 0 0 1.944-1.562l.957-4.299a.175.175 0 0 0-.173-.21z'
    })
  ])
}

// 类型定义
interface AssetDimensions {
  width: number
  height: number
}

interface AssetRequirements {
  softwareVersion?: string
  plugins?: string
}

interface AssetComment {
  id: string
  username: string
  userAvatar: string
  rating: number
  content: string
  createdAt: Date
  likes: number
  isLiked: boolean
  replies?: AssetCommentReply[]
}

interface AssetCommentReply {
  id: string
  username: string
  userAvatar: string
  content: string
  createdAt: Date
}

interface Asset {
  id: string
  name: string
  type: string
  thumbnail: string
  previewImages?: string[]
  price: number
  rating: number
  ratingCount: number
  ratingDistribution: Record<number, number>
  creator: string
  creatorId: string
  creatorAvatar: string
  tags: string[]
  isNew: boolean
  downloadCount: number
  viewCount: number
  createdAt: Date
  description: string
  shortDescription: string
  fileFormat: string
  fileSize: number
  dimensions?: AssetDimensions
  duration?: number
  requirements?: AssetRequirements
  license: string
  comments: AssetComment[]
  isFeatured: boolean
}

interface ReportReason {
  value: string
  label: string
}

// 路由和消息
const route = useRoute()
const router = useRouter()
const message = useMessage()

// 状态
const loading = ref(true)
const downloading = ref(false)
const asset = ref<Asset | null>(null)
const relatedAssets = ref<Partial<Asset>[]>([])
const currentPreviewIndex = ref(0)
const isFavorite = ref(false)
const isLoggedIn = ref(false) // 实际项目中应从用户状态中获取

// 评论相关
const userRating = ref(0)
const commentContent = ref('')
const commentPage = ref(1)
const commentTotalPages = computed(() => {
  if (!asset.value) return 1
  return Math.ceil(asset.value.comments.length / 5)
})

// 模态框状态
const showPreview = ref(false)
const showShare = ref(false)
const showReport = ref(false)
const reportReason = ref('')
const reportDetail = ref('')
const reportReasons: ReportReason[] = [
  { value: 'copyright', label: '侵犯版权' },
  { value: 'inappropriate', label: '内容不适当' },
  { value: 'quality', label: '质量问题' },
  { value: 'misleading', label: '描述误导' },
  { value: 'other', label: '其他问题' }
]

// 计算属性
const formattedDescription = computed(() => {
  if (!asset.value) return ''
  // 简单的HTML格式化，实际项目中可能需要更安全的处理
  return asset.value.description.replace(/\n/g, '<br>')
})

const canDownload = computed(() => {
  if (!asset.value) return false
  // 免费素材可直接下载，付费素材需要登录
  return asset.value.price === 0 || isLoggedIn.value
})

const canPreview = computed(() => {
  if (!asset.value) return false
  return asset.value.previewImages && asset.value.previewImages.length > 0
})

const canSubmitComment = computed(() => {
  return isLoggedIn.value && userRating.value > 0 && commentContent.value.trim().length > 0
})

const canSubmitReport = computed(() => {
  if (!reportReason.value) return false
  if (reportReason.value === 'other') {
    return reportDetail.value.trim().length > 0
  }
  return true
})

const shareLink = computed(() => {
  return `${window.location.origin}/asset-detail/${route.params.id}`
})

// 方法
function getAssetTypeLabel(type: string): string {
  switch (type) {
    case 'character': return '角色素材'
    case 'scene': return '场景素材'
    case 'prop': return '道具素材'
    case 'audio': return '音频素材'
    case 'animation': return '动画素材'
    default: return '素材'
  }
}

function getLicenseLabel(license: string): string {
  switch (license) {
    case 'free': return '免费使用'
    case 'premium': return '商业授权'
    case 'cc0': return 'CC0'
    case 'cc-by': return 'CC BY'
    case 'cc-by-sa': return 'CC BY-SA'
    case 'cc-by-nc': return 'CC BY-NC'
    default: return '标准授权'
  }
}

function getLicenseTagType(license: string): 'success' | 'warning' | 'info' | 'default' | 'error' | 'primary' {
  switch (license) {
    case 'free':
      return 'success'
    case 'premium':
      return 'warning'
    case 'cc0':
      return 'info'
    case 'cc-by':
      return 'info'
    case 'cc-by-sa':
      return 'info'
    default:
      return 'default'
  }
}

function getLicenseDescription(license: string): string {
  switch (license) {
    case 'free':
      return '免费使用授权：您可以在个人项目中免费使用此素材，但不得用于商业用途。'
    case 'premium':
      return '商业授权：购买后，您可以在个人和商业项目中无限制使用此素材。'
    case 'cc0':
      return 'CC0：此作品已被作者无条件释放到公共领域，您可以自由使用、修改和分发，无需署名。'
    case 'cc-by':
      return 'CC BY：您可以自由使用、修改和分发此作品，但必须署名原作者。'
    case 'cc-by-sa':
      return 'CC BY-SA：您可以自由使用、修改和分发此作品，但必须署名原作者并以相同方式共享。'
    case 'cc-by-nc':
      return 'CC BY-NC：您可以自由使用、修改和分发此作品，但必须署名原作者且不得用于商业用途。'
    default:
      return '标准授权：购买后，您可以在个人项目中使用此素材，商业用途需额外授权。'
  }
}

function formatDate(date: Date): string {
  if (!date) return ''
  return new Date(date).toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  })
}

function formatFileSize(size: number): string {
  if (size < 1024) {
    return `${size} B`
  } else if (size < 1024 * 1024) {
    return `${(size / 1024).toFixed(2)} KB`
  } else if (size < 1024 * 1024 * 1024) {
    return `${(size / (1024 * 1024)).toFixed(2)} MB`
  } else {
    return `${(size / (1024 * 1024 * 1024)).toFixed(2)} GB`
  }
}

function formatDuration(ms: number): string {
  const seconds = Math.floor(ms / 1000)
  const minutes = Math.floor(seconds / 60)
  const hours = Math.floor(minutes / 60)
  
  if (hours > 0) {
    return `${hours}时${minutes % 60}分${seconds % 60}秒`
  } else if (minutes > 0) {
    return `${minutes}分${seconds % 60}秒`
  } else {
    return `${seconds}秒`
  }
}

function getDistributionPercentage(stars: number): number {
  if (!asset.value) return 0
  
  const count = asset.value.ratingDistribution[stars] || 0
  if (asset.value.ratingCount === 0) return 0
  
  return (count / asset.value.ratingCount) * 100
}

function goBack(): void {
  router.back()
}

function downloadAsset(): void {
  if (!asset.value) return
  
  if (asset.value.price > 0 && isLoggedIn.value) {
    // 付费素材，显示购买确认
    showPurchaseConfirmation()
  } else if (asset.value.price > 0 && !isLoggedIn.value) {
    // 未登录，提示登录
    message.info('请先登录再购买素材')
    goToLogin()
  } else {
    // 免费素材，直接下载
    startDownload()
  }
}

function showPurchaseConfirmation(): void {
  // 实际项目中应使用对话框组件
  if (confirm(`确认使用 ${asset.value!.price} 积分购买此素材吗？`)) {
    startDownload()
  }
}

function startDownload(): void {
  if (!asset.value) return
  
  downloading.value = true
  
  // 模拟下载过程
  setTimeout(() => {
    downloading.value = false
    message.success('资源下载成功')
    
    // 更新下载次数（实际项目中应通过API更新）
    if (asset.value) {
      asset.value.downloadCount++
    }
  }, 2000)
}

function previewAsset(): void {
  if (!canPreview.value) return
  showPreview.value = true
}

function toggleFavorite(): void {
  if (!isLoggedIn.value) {
    message.info('请先登录再收藏素材')
    goToLogin()
    return
  }
  
  isFavorite.value = !isFavorite.value
  message.success(isFavorite.value ? '已添加到收藏' : '已取消收藏')
}

function shareAsset(): void {
  showShare.value = true
}

function shareToSocial(platform: string): void {
  // 实际项目中应实现社交分享功能
  message.success(`已分享到${platform}`)
  showShare.value = false
}

function copyShareLink(): void {
  // 实际项目中应使用clipboard API
  navigator.clipboard.writeText(shareLink.value)
    .then(() => {
      message.success('链接已复制到剪贴板')
    })
    .catch(() => {
      message.error('复制失败，请手动复制')
    })
}

function reportAsset(): void {
  if (!isLoggedIn.value) {
    message.info('请先登录再举报素材')
    goToLogin()
    return
  }
  
  showReport.value = true
}

function cancelReport(): void {
  showReport.value = false
  reportReason.value = ''
  reportDetail.value = ''
}

function handleReportSubmit(): void {
  if (!reportReason.value) {
    message.error('请选择举报原因')
    return
  }
  
  submittingReport.value = true
  // 模拟提交过程
  setTimeout(() => {
    submittingReport.value = false
    showReport.value = false
    message.success('举报已提交，我们将尽快处理')
    reportReason.value = ''
    reportDetail.value = ''
  }, 1000)
}

function viewCreator(): void {
  if (!asset.value) return
  router.push(`/user-profile/${asset.value.creatorId}`)
}

function searchByTag(tag: string): void {
  router.push({
    path: '/market',
    query: { tag }
  })
}

function submitComment(): void {
  if (!canSubmitComment.value || !asset.value) return
  
  // 实际项目中应调用API提交评论
  const newComment: AssetComment = {
    id: `comment-${Date.now()}`,
    username: '当前用户',
    userAvatar: 'https://i.pravatar.cc/100?img=1',
    rating: userRating.value,
    content: commentContent.value,
    createdAt: new Date(),
    likes: 0,
    isLiked: false,
    replies: []
  }
  
  asset.value.comments.unshift(newComment)
  
  // 更新评分
  updateAssetRating(userRating.value)
  
  // 重置表单
  userRating.value = 0
  commentContent.value = ''
  
  message.success('评价已提交')
}

function updateAssetRating(newRating: number): void {
  if (!asset.value) return
  
  // 更新评分分布
  if (!asset.value.ratingDistribution[newRating]) {
    asset.value.ratingDistribution[newRating] = 0
  }
  asset.value.ratingDistribution[newRating]++
  
  // 更新总评分和评分人数
  const totalScore = Object.entries(asset.value.ratingDistribution).reduce(
    (sum, [rating, count]) => sum + (Number(rating) * count),
    0
  )
  asset.value.ratingCount++
  asset.value.rating = totalScore / asset.value.ratingCount
}

function likeComment(comment: AssetComment): void {
  if (!isLoggedIn.value) {
    message.info('请先登录再点赞')
    goToLogin()
    return
  }
  
  comment.isLiked = !comment.isLiked
  comment.likes += comment.isLiked ? 1 : -1
}

function replyComment(comment: AssetComment): void {
  if (!isLoggedIn.value) {
    message.info('请先登录再回复')
    goToLogin()
    return
  }
  
  // 实际项目中应显示回复表单
  const replyContent = prompt('请输入回复内容:')
  if (replyContent) {
    if (!comment.replies) {
      comment.replies = []
    }
    
    comment.replies.push({
      id: `reply-${Date.now()}`,
      username: '当前用户',
      userAvatar: 'https://i.pravatar.cc/100?img=1',
      content: replyContent,
      createdAt: new Date()
    })
  }
}

function viewMoreRelated(): void {
  router.push({
    path: '/market',
    query: { type: asset.value?.type }
  })
}

function viewAsset(id: string): void {
  router.push(`/asset-detail/${id}`)
}

function goToLogin(): void {
  router.push({
    path: '/account/login',
    query: { redirect: router.currentRoute.value.fullPath }
  })
}

// 生命周期钩子
onMounted(() => {
  fetchAssetDetail()
})

// 模拟API请求
function fetchAssetDetail(): void {
  const assetId = route.params.id as string
  
  // 模拟加载延迟
  setTimeout(() => {
    // 生成模拟数据
    generateMockAssetDetail(assetId)
    loading.value = false
  }, 1000)
}

// 生成模拟数据
function generateMockAssetDetail(assetId: string): void {
  // 随机生成评分分布
  const ratingDistribution: Record<number, number> = {}
  let totalRatings = 0
  
  for (let i = 1; i <= 5; i++) {
    const count = Math.floor(Math.random() * 20) + (i === 5 ? 30 : i === 4 ? 20 : 5)
    ratingDistribution[i] = count
    totalRatings += count
  }
  
  // 计算平均评分
  const totalScore = Object.entries(ratingDistribution).reduce(
    (sum, [rating, count]) => sum + (Number(rating) * count),
    0
  )
  const averageRating = totalScore / totalRatings
  
  // 生成评论
  const comments: AssetComment[] = []
  for (let i = 0; i < 8; i++) {
    const rating = Math.floor(Math.random() * 3) + 3 // 3-5星
    
    const comment: AssetComment = {
      id: `comment-${i}`,
      username: `用户${i + 1}`,
      userAvatar: `https://i.pravatar.cc/100?img=${i + 10}`,
      rating,
      content: `这是一条评价内容，对这个素材的使用体验很${rating >= 4 ? '满意' : '一般'}。${
        rating === 5 ? '非常推荐使用！' : rating === 4 ? '值得使用。' : '还可以改进。'
      }`,
      createdAt: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000),
      likes: Math.floor(Math.random() * 10),
      isLiked: false
    }
    
    // 随机添加回复
    if (Math.random() > 0.6) {
      comment.replies = [
        {
          id: `reply-${i}-1`,
          username: '创作者',
          userAvatar: 'https://i.pravatar.cc/100?img=5',
          content: '感谢您的评价和反馈！',
          createdAt: new Date(Date.now() - Math.random() * 15 * 24 * 60 * 60 * 1000)
        }
      ]
    }
    
    comments.push(comment)
  }
  
  // 生成预览图
  const previewImages = []
  for (let i = 0; i < 4; i++) {
    previewImages.push(`https://picsum.photos/id/${Number(assetId.replace('asset-', '')) + i + 200}/800/600`)
  }
  
  // 生成素材详情
  asset.value = {
    id: assetId,
    name: `示例素材 ${assetId}`,
    type: ['character', 'scene', 'prop', 'audio', 'animation'][Math.floor(Math.random() * 5)],
    thumbnail: `https://picsum.photos/id/${Number(assetId.replace('asset-', '')) + 100}/800/600`,
    previewImages,
    price: Math.random() > 0.3 ? Math.floor(Math.random() * 500) + 50 : 0,
    rating: averageRating,
    ratingCount: totalRatings,
    ratingDistribution,
    creator: '示例创作者',
    creatorId: 'creator-1',
    creatorAvatar: 'https://i.pravatar.cc/100?img=5',
    tags: ['中国风', '现代', '古风', '科幻', '卡通'].sort(() => 0.5 - Math.random()).slice(0, 3),
    isNew: Math.random() > 0.7,
    downloadCount: Math.floor(Math.random() * 1000),
    viewCount: Math.floor(Math.random() * 5000),
    createdAt: new Date(Date.now() - Math.random() * 90 * 24 * 60 * 60 * 1000),
    description: `这是一个高质量的素材，适用于各种创作场景。\n\n特点：\n- 高清分辨率\n- 可自定义颜色\n- 多种风格选择\n\n使用方法：\n下载后导入到项目中即可使用，支持各种主流软件。`,
    shortDescription: '高质量素材，适用于各种创作场景',
    fileFormat: ['PNG', 'JPG', 'SVG', 'MP3', 'MP4'][Math.floor(Math.random() * 5)],
    fileSize: Math.floor(Math.random() * 100 * 1024 * 1024), // 0-100MB
    dimensions: {
      width: [1920, 3840, 1280, 2560][Math.floor(Math.random() * 4)],
      height: [1080, 2160, 720, 1440][Math.floor(Math.random() * 4)]
    },
    duration: Math.random() > 0.5 ? Math.floor(Math.random() * 300) * 1000 : undefined, // 0-300秒
    requirements: {
      softwareVersion: '1.0.0及以上',
      plugins: Math.random() > 0.7 ? '无' : '高级特效插件'
    },
    license: ['free', 'premium', 'cc0', 'cc-by', 'cc-by-sa'][Math.floor(Math.random() * 5)],
    comments,
    isFeatured: Math.random() > 0.5
  }
  
  // 生成相关素材
  generateRelatedAssets()
}

function generateRelatedAssets(): void {
  if (!asset.value) return
  
  const related: Partial<Asset>[] = []
  
  for (let i = 1; i <= 4; i++) {
    const id = `asset-${Math.floor(Math.random() * 100) + 100}`
    
    related.push({
      id,
      name: `相关素材 ${i}`,
      type: asset.value.type,
      thumbnail: `https://picsum.photos/id/${300 + i}/300/200`,
      price: Math.random() > 0.3 ? Math.floor(Math.random() * 500) + 50 : 0,
      rating: Math.random() * 2 + 3, // 3-5星
      creator: '示例创作者',
      tags: [...asset.value.tags].sort(() => 0.5 - Math.random()).slice(0, 2)
    })
  }
  
  relatedAssets.value = related
}
</script>

<style lang="scss" scoped>
.asset-detail-container {
  padding: 20px;
  height: 100%;
  overflow-y: auto;
  
  .detail-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      h1 {
        margin: 0;
        font-size: 24px;
        font-weight: 500;
      }
      
      .header-actions {
        display: flex;
        gap: 12px;
      }
    }
  }
  
  .loading-container, .error-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 60px 0;
    
    p {
      margin-top: 16px;
      color: var(--text-color-secondary);
    }
  }
  
  .asset-content {
    .asset-main {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 24px;
      margin-bottom: 30px;
      
      .asset-preview {
        .preview-container {
          border: 1px solid var(--border-color);
          border-radius: 4px;
          overflow: hidden;
          margin-bottom: 16px;
          
          img {
            width: 100%;
            display: block;
          }
          
          .preview-controls {
            padding: 12px;
            background-color: var(--card-color);
            border-top: 1px solid var(--border-color);
            
            .preview-thumbnails {
              display: flex;
              gap: 8px;
              overflow-x: auto;
              padding-bottom: 4px;
              
              .preview-thumbnail {
                width: 60px;
                height: 40px;
                border-radius: 2px;
                overflow: hidden;
                cursor: pointer;
                border: 2px solid transparent;
                opacity: 0.7;
                transition: all 0.2s;
                
                &.active {
                  border-color: var(--primary-color);
                  opacity: 1;
                }
                
                &:hover {
                  opacity: 0.9;
                }
                
                img {
                  width: 100%;
                  height: 100%;
                  object-fit: cover;
                }
              }
            }
          }
        }
        
        .asset-actions {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 16px;
        }
      }
      
      .asset-info {
        .asset-header {
          display: flex;
          justify-content: space-between;
          align-items: flex-start;
          margin-bottom: 16px;
          
          h2 {
            margin: 0;
            font-size: 20px;
            font-weight: 500;
            flex: 1;
          }
          
          .asset-badges {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            margin-left: 16px;
          }
        }
        
        .asset-meta {
          margin-bottom: 24px;
          
          .meta-item {
            display: flex;
            align-items: center;
            margin-bottom: 8px;
            color: var(--text-color-secondary);
            
            .n-icon {
              margin-right: 8px;
            }
            
            span {
              margin-right: 4px;
            }
            
            .n-button {
              padding: 0;
              font-size: inherit;
            }
          }
        }
        
        .asset-rating {
          margin-bottom: 24px;
          padding: 16px;
          background-color: var(--card-color);
          border-radius: 4px;
          border: 1px solid var(--border-color);
          
          .rating-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 8px;
            
            h3 {
              margin: 0;
              font-size: 16px;
              font-weight: 500;
            }
            
            span {
              font-size: 20px;
              font-weight: bold;
              color: var(--warning-color);
            }
          }
          
          .rating-stars {
            display: flex;
            align-items: center;
            margin-bottom: 16px;
            
            span {
              margin-left: 8px;
              color: var(--text-color-secondary);
              font-size: 14px;
            }
          }
          
          .rating-distribution {
            .rating-bar {
              display: flex;
              align-items: center;
              margin-bottom: 4px;
              
              span {
                width: 40px;
                font-size: 12px;
                color: var(--text-color-secondary);
                
                &:last-child {
                  width: 30px;
                  text-align: right;
                }
              }
              
              .bar-container {
                flex: 1;
                height: 8px;
                background-color: var(--divider-color);
                border-radius: 4px;
                margin: 0 8px;
                overflow: hidden;
                
                .bar-fill {
                  height: 100%;
                  background-color: var(--warning-color);
                  border-radius: 4px;
                }
              }
            }
          }
        }
        
        .asset-tags {
          h3 {
            margin: 0 0 12px;
            font-size: 16px;
            font-weight: 500;
          }
          
          .tags-list {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            
            .n-tag {
              cursor: pointer;
            }
          }
        }
      }
    }
    
    .asset-details {
      margin-bottom: 30px;
      
      .description-content {
        padding: 16px;
        line-height: 1.6;
      }
      
      .specifications-content {
        .spec-group {
          margin-bottom: 24px;
          
          h3 {
            margin: 0 0 12px;
            font-size: 16px;
            font-weight: 500;
          }
          
          .spec-table {
            .spec-row {
              display: flex;
              padding: 8px 0;
              border-bottom: 1px solid var(--divider-color);
              
              &:last-child {
                border-bottom: none;
              }
              
              .spec-label {
                width: 120px;
                color: var(--text-color-secondary);
              }
              
              .spec-value {
                flex: 1;
              }
            }
          }
          
          .license-info {
            p {
              line-height: 1.6;
              margin: 0;
            }
          }
        }
      }
      
      .comments-content {
        .comment-form {
          margin-bottom: 24px;
          
          h3 {
            margin: 0 0 16px;
            font-size: 16px;
            font-weight: 500;
          }
          
          .rating-input {
            display: flex;
            align-items: center;
            margin-bottom: 12px;
            
            span {
              margin-right: 8px;
            }
          }
          
          .form-actions {
            margin-top: 12px;
            text-align: right;
          }
        }
        
        .login-prompt {
          text-align: center;
          padding: 16px;
          color: var(--text-color-secondary);
        }
        
        .comments-list {
          h3 {
            margin: 0 0 16px;
            font-size: 16px;
            font-weight: 500;
          }
          
          .empty-comments {
            padding: 24px 0;
          }
          
          .comment-items {
            .comment-item {
              margin-bottom: 24px;
              padding-bottom: 16px;
              border-bottom: 1px solid var(--divider-color);
              
              &:last-child {
                border-bottom: none;
              }
              
              .comment-header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-bottom: 12px;
                
                .comment-user {
                  display: flex;
                  align-items: center;
                  
                  .username {
                    margin-left: 8px;
                    font-weight: 500;
                  }
                }
              }
              
              .comment-content {
                margin-bottom: 12px;
                line-height: 1.6;
              }
              
              .comment-footer {
                display: flex;
                justify-content: space-between;
                align-items: center;
                
                .comment-time {
                  color: var(--text-color-secondary);
                  font-size: 12px;
                }
                
                .comment-actions {
                  display: flex;
                  gap: 12px;
                }
              }
              
              .comment-replies {
                margin-top: 16px;
                margin-left: 24px;
                padding-left: 16px;
                border-left: 2px solid var(--divider-color);
                
                .reply-item {
                  margin-bottom: 12px;
                  
                  &:last-child {
                    margin-bottom: 0;
                  }
                  
                  .reply-header {
                    display: flex;
                    align-items: center;
                    margin-bottom: 8px;
                    
                    .reply-user {
                      display: flex;
                      align-items: center;
                      
                      .username {
                        margin-left: 8px;
                        font-weight: 500;
                        font-size: 14px;
                      }
                    }
                  }
                  
                  .reply-content {
                    margin-bottom: 8px;
                    line-height: 1.5;
                    font-size: 14px;
                  }
                  
                  .reply-footer {
                    .reply-time {
                      color: var(--text-color-secondary);
                      font-size: 12px;
                    }
                  }
                }
              }
            }
          }
          
          .comments-pagination {
            display: flex;
            justify-content: center;
            margin-top: 24px;
          }
        }
      }
    }
    
    .related-assets {
      .section-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;
        
        h2 {
          margin: 0;
          font-size: 18px;
          font-weight: 500;
        }
      }
      
      .related-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
        gap: 16px;
        
        .asset-card {
          cursor: pointer;
          transition: transform 0.2s, box-shadow 0.2s;
          
          &:hover {
            transform: translateY(-4px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
          }
          
          .asset-thumbnail {
            position: relative;
            height: 140px;
            overflow: hidden;
            border-radius: 3px;
            
            img {
              width: 100%;
              height: 100%;
              object-fit: cover;
            }
            
            .asset-badges {
              position: absolute;
              top: 8px;
              right: 8px;
              display: flex;
              flex-direction: column;
              gap: 4px;
            }
          }
          
          .asset-info {
            padding: 12px 0 0;
            
            h3 {
              margin: 0 0 8px;
              font-size: 14px;
              font-weight: 500;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }
            
            .asset-meta {
              display: flex;
              justify-content: space-between;
              align-items: center;
              
              .asset-creator {
                font-size: 12px;
                color: var(--text-color-secondary);
              }
            }
          }
        }
      }
    }
  }
  
  .preview-modal-content {
    .preview-description {
      margin-top: 16px;
      
      h3 {
        margin: 0 0 8px;
        font-size: 18px;
      }
      
      p {
        margin: 0;
        color: var(--text-color-secondary);
      }
    }
  }
  
  .share-modal-content {
    .share-buttons {
      display: flex;
      justify-content: center;
      gap: 16px;
      margin: 16px 0;
    }
    
    .share-link {
      margin-top: 16px;
    }
  }
  
  .report-modal-content {
    .modal-actions {
      display: flex;
      justify-content: flex-end;
      gap: 12px;
      margin-top: 24px;
    }
  }
}

/* 响应式调整 */
@media (max-width: 768px) {
  .asset-detail-container {
    padding: 12px;
    
    .asset-content {
      .asset-main {
        grid-template-columns: 1fr;
      }
      
      .related-grid {
        grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
      }
    }
  }
}
</style> 